package com.letou.ls.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by tengxp on 16/3/14.
 */
public class VerticalTextView extends ScrollView {
    public static final int SCROLL_DISTANCE = 2;
    public static final int WAITING_TIME = 1000;

//    public static final Pattern CHINESE = Pattern.compile("[\u4e00-\u9fa5]");
    public static final Pattern CHINESE = Pattern.compile("([\u4e00-\u9fa5]+)");
    public static final Pattern NUMBER = Pattern.compile("[0-9]*");

    private boolean isPlaying;
    private int startY;
    private long lastTime = System.currentTimeMillis();

    private int textSize = 20;

    private LinearLayout mParent;
    private Runnable mRunnable = new Runnable() {

        @Override
        public void run() {
            int y = getScrollY();
            long time = System.currentTimeMillis();
            if (startY == y || time - lastTime < WAITING_TIME) {
                scrollTo(y, 0);

                startY = -1;
                if (time - lastTime > WAITING_TIME) lastTime = time;
            } else {
                smoothScrollBy(10, SCROLL_DISTANCE);

                if (y > 0) startY = y;
            }
        }
    };

    public VerticalTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setHorizontalScrollBarEnabled(false);
        setVerticalScrollBarEnabled(false);

        mParent = new LinearLayout(context);
        int wrapContent = ViewGroup.LayoutParams.WRAP_CONTENT;
        mParent.setLayoutParams(new LayoutParams(wrapContent, wrapContent));
//        mParent.setHorizontalGravity(Gravity.CENTER_HORIZONTAL);
        mParent.setGravity(Gravity.CENTER_HORIZONTAL);
        mParent.setOrientation(LinearLayout.VERTICAL);

        setFocusable(false);
        setFocusableInTouchMode(false);

        addView(mParent);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        System.out.println("onAttachedToWindow");

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                play();
            }
        }, "scrollText");

        isPlaying = true;
        thread.start();

        requestLayout();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        System.out.println("onDetachedFromWindow");

        isPlaying = false;
    }

    public void setText(String text) {
        System.out.println("setText : " + text);
        mParent.removeAllViewsInLayout();

        List<String> list = split(text);
        for (int i = 0; i < list.size(); i ++) {
            mParent.addView(obtainTextView(list.get(i)));
        }

        mParent.requestLayout();
    }

    public void setTextSize(int textSize) {
        this.textSize = textSize;
    }

    private TextView obtainTextView(String text) {

        TextView textView = new TextView(getContext());
        textView.setLayoutParams(new LinearLayout.LayoutParams(-2, -2));
        textView.setGravity(Gravity.CENTER_HORIZONTAL);
        textView.setTextColor(Color.BLACK);
        textView.setTextSize(textSize);

        textView.setText(text);

        boolean isChinese = text.length() != 1;
        textView.setRotation(isChinese ? 0 : 90);
        if (!isChinese) {
//            textView.setMaxHeight(25);
//            textView.setBackgroundColor(Color.YELLOW);
//            textView.setGravity(Gravity.CENTER_VERTICAL);
        }

        return textView;
    }

    private List<String> split(String text) {
        String[] array = CHINESE.split(text);
        System.out.println(Arrays.toString(array));

        ArrayList<String> list = new ArrayList<String>();
        // head
        int index;
        for (String s : array) {
            index = text.indexOf(s);
            if (index > 0) {
                list.add(text.substring(0, index));
            }

            for (int i = 0; i < s.length(); i++) {
                list.add(s.substring(i, i + 1));
            }

            text = text.substring(index + s.length());
        }

        if (text != null && text.length() > 0) list.add(text);

        array = new String[list.size()];
        System.out.println(Arrays.toString(list.toArray(array)));
        return list;
    }

    private synchronized void play() {
        System.out.println("play : start ");
        while (isPlaying) {
            try {
                Thread.currentThread().sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            post(mRunnable);
        }
        System.out.println("play : stop");
    }
}
